package LeetCode;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/4/16.
// 
public class 两数相加 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        ListNode l1 = new ListNode(9,null);
        ListNode l2 = new ListNode(1,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,null)))))))));
        ListNode node = addTwoNumbers(l1,l2);
        while(node != null){
            System.out.print(node.val + " ");
            node = node.next;
        }
    }



    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l = new ListNode();
        ListNode point = l;
        while(l1!=null && l2 !=null){
            point.val = l1.val+l2.val;
            l1 = l1.next;
            l2 = l2.next;
            if(l1 != null && l2 != null){
                point.next = new ListNode();
                point = point.next;
            }
        }
        while(l1 != null){
            point.next = new ListNode();
            point = point.next;
            point.val = l1.val;
            l1 = l1.next;
        }
        while(l2 != null){
            point.next = new ListNode();
            point = point.next;
            point.val = l2.val;
            l2 = l2.next;
        }
        point = l;
        while(point != null){
            if(point.val > 9){
                point.val %= 10;
                if(point.next == null){
                    point.next = new ListNode(1,null);
                }else {
                    point.next.val += 1;
                }
            }
            point = point.next;
        }
        return l;
    }
}
